<template>
  <ContainerGroup>
    <Container style="margin-bottom:10px;">
      <FilterForm
        ref="filterForm"
        :elements="filterElements"
        @submit="handleSearch"
        @reset="handlerReset"
      >
        <Button icon="add" @click="handleAdd">新增</Button>
        <Button type="info" icon="cloudy" :loading="xzmbLoading" @click="handleExport(0)">下载模板</Button>
        <el-upload
          ref="upload"
          style="display:inline-block;"
          :show-file-list="false"
          :on-change="handlechange"
          class="upload-demo"
          action
          :auto-upload="false"
        >
          <el-button size="mini" :loading="drLoading" class="btn-import el-icon-upload2">导入</el-button>
        </el-upload>
        <Button type="info" :loading="dcLoading" icon="export" @click="handleExport(1)">导出</Button>
      </FilterForm>
    </Container>
    <Container height="fill" display="flexY">
      <Table
        :columns="tableColumns"
        :loading="tableLoading"
        :data="tableData"
        :pagination="{
          total: total,
          current: currentPage,
          pageSize: pageSize,
        }"
        @paginationChange="pageChange"
      >
        <template #enableFlag="{row}">
          <el-switch
            v-model="row.enableFlag"
            :width="50"
            active-color="#217dfa"
            inactive-color="#E5E5E5"
            :active-value="1"
            :inactive-value="0"
            @change="handleChangeSwitch(row)"
          />
        </template>
        <template #caozuo="{ row }">
          <Tooltip content="编辑" icon="edit" @click="handleEidt(row)" />
          <Tooltip content="删除" icon="delete" @click="handleDelete(row)" />
        </template>
      </Table>
      <!-- 新增、编辑 -->
      <Drawer
        :title="title"
        :visible="isShow"
        :header-color="'#e7ecf8'"
        width="500px"
        :loading="confirmLoading"
        :footer-btns="[
          {
            text: '确定',
            type: 'primary',
            trigger: 'submit',
          },
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @cancel="isShow = false"
        @submit="handleSubmit"
      >
        <el-form
          ref="ruleForm"
          size="mini"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="数据项名称" prop="entryName">
            <el-input v-model.trim="ruleForm.entryName" placeholder="请输入数据项名称" />
          </el-form-item>
          <el-form-item label="数据项编码">
            <el-input v-model.trim="ruleForm.entryCode" placeholder="请输入数据项编码" />
          </el-form-item>
          <el-form-item label="排序">
            <el-input v-model.trim="ruleForm.entryOrder" placeholder="请输入排序" />
          </el-form-item>
          <el-form-item label="描述">
            <el-input
              v-model.trim="ruleForm.entryDescription"
              type="textarea"
              :rows="5"
              placeholder="请输入描述"
              maxlength="300"
            />
          </el-form-item>
          <el-form-item label="是否启用">
            <el-switch
              v-model="ruleForm.enableFlag"
              :width="50"
              active-color="#217dfa"
              inactive-color="#E5E5E5"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-form>
      </Drawer>
    </Container>
  </ContainerGroup>
</template>
<script>
import {
  zxDataentryPage,
  zxDataentryDelete,
  zxDataentrySave,
  zxDataentryUpdate,
  zxDataentryUnEnable,
  zxDataentryDownload,
  zxDataentrySaveFile
} from '@/apis/specialFunds/systermSetting'
export default {
  name: 'DataDictionaries', // 数据字典
  data() {
    return {
      confirmLoading: false,
      ruleForm: {
        entryName: '',
        entryCode: '',
        entryOrder: '',
        entryDescription: '',
        enableFlag: 1
      },
      rules: {
        entryName: [
          { required: true, message: '请输入数据项名称', trigger: 'blur' }
        ]
      },
      filterElements: [
        {
          key: 'entryName',
          type: 'input',
          label: '数据项名称',
          value: ''
        }
      ],
      title: '添加数据项',
      tableColumns: [
        {
          title: '数据项名称',
          dataIndex: 'entryName',
          width: 300
        },
        {
          title: '数据项编码',
          dataIndex: 'entryCode',
          width: 100
        },
        {
          title: '排序',
          dataIndex: 'entryOrder',
          width: 80
        },
        {
          title: '是否启用',
          dataIndex: 'enableFlag',
          type: 'otherTag',
          width: 80
        },
        {
          title: '描述',
          dataIndex: 'entryDescription'
        },
        {
          title: '操作',
          width: 160,
          dataIndex: 'caozuo',
          type: 'otherTag'
        }
      ],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      tableLoading: false,
      tableData: [],
      newCondition: {},
      isShow: false,
      btnType: 1,
      rowData: null,
      xzmbLoading: false,
      dcLoading: false,
      drLoading: false
    }
  },
  created() {},
  methods: {
    handleChangeSwitch(row) {
      const param = {
        id: row.id,
        enableFlag: row.enableFlag
      }
      zxDataentryUnEnable(param).then(res => {
        this.handleClearForm()
        if (res.data.code === 200) {
          this.$message.success(res.data.message)
          this.getData()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    handlechange(file, fileList) {
      // 导入
      const fileType = file.name.substr(file.name.lastIndexOf('.')).trim()
      if (fileType !== '.xlsx' && fileType !== '.xls') {
        this.$message.warning('请选择Excel格式的文件导入！')
        return
      }
      const files = file.raw
      const formData = new FormData()
      formData.append('file', files)
      const param = {
        formData: formData
      }
      zxDataentrySaveFile(param).then((res) => {
        if (res.data.code === 200) {
          this.$message.success('上传成功')
          this.getData()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    handleExport(type) {
      // 导出
      const param = {
        entryName: this.$refs.filterForm.getParms()?.entryName || '',
        dictCode: this.$route.query.id,
        isMoBan: type // 0表示下载模版，1表示下载文件
      }
      this.dcLoading = true
      zxDataentryDownload(param).then(res => {
        this.dcLoading = false
        const blob = new Blob([res.data], {
          type: res.data.type + 'charset=utf-8'
        })
        const downloadLink = document.createElement('a')
        const URL = window.URL || window.webkitURL || window.moxURL
        const downUrl = URL.createObjectURL(blob)
        downloadLink.href = downUrl
        downloadLink.download = '数据项.xlsx'
        downloadLink.click()
        window.URL.revokeObjectURL(downUrl)
        // document.body.removeChild(downloadLink) // 删除 a 标签
      })
    },
    handleSubmit() {
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          // console.log('---------', !/^\d*$/.test(this.ruleForm.entryOrder))
          if (
            this.ruleForm.entryOrder &&
            !/^\d*$/.test(this.ruleForm.entryOrder)
          ) {
            this.$message.warning('排序需要输入正整数')
            return
          }
          const param = {
            ...this.ruleForm
          }
          param.dictCode = this.$route.query.id
          this.confirmLoading = true
          let api = zxDataentrySave
          if (this.btnType === 2) {
            // 编辑
            param.id = this.rowData.id
            api = zxDataentryUpdate
          }
          api(param).then(res => {
            this.confirmLoading = false
            this.isShow = false
            if (res.data.code === 200) {
              this.$message.success(res.data.message)
              this.getData()
            } else {
              this.$message.error(res.data.message)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleClearForm() {
      for (const key in this.ruleForm) {
        if (key === 'enableFlag') {
          this.ruleForm[key] = 1
        }
        this.ruleForm[key] = ''
      }
    },
    handleEidt(row) {
      // 编辑
      this.title = '编辑数据项'
      this.rowData = row
      this.btnType = 2
      this.isShow = true
      this.handleClearForm()
      this.setDetails(this.rowData)
    },
    setDetails(row) {
      for (const key in this.ruleForm) {
        this.ruleForm[key] = row[key]
      }
    },
    handleDelete(row) {
      this.$confirm({
        content: '是否确认删除该条数据项？',
        title: '温馨提示',
        okFn: res => {
          zxDataentryDelete(row.id).then(res => {
            if (res.data.code === 200) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.getData()
            }
          })
        },
        cancelFn: res => {
          console.log('取消')
        }
      })
    },
    handleAdd() {
      this.title = '添加数据项'
      this.btnType = 1
      this.isShow = true
      this.handleClearForm()
    },
    handleSearch(value) {
      this.newCondition = value
      this.currentPage = 1
      this.getData()
    },
    getData() {
      const params = {
        dictCode: this.$route.query.id,
        entryName: this.newCondition?.entryName,
        pageNo: this.currentPage,
        pageSize: this.pageSize
      }
      this.tableLoading = true
      zxDataentryPage(params)
        .then(res => {
          this.tableLoading = false
          if (res.data.code === 200) {
            this.tableData = res.data.data.list
            this.total = res.data.data.total
          } else {
            this.$message.error(res.data.message)
          }
        })
        .catch(() => {
          this.tableLoading = false
        })
    },
    handlerReset(val) {
      this.handleSearch()
    },
    pageChange(payload) {
      this.currentPage = payload.current
      this.pageSize = payload.pageSize
      this.getData()
    }
  }
}
</script>
<style lang="less" scoped>
.demo-ruleForm {
  margin: 10px 15px;
}
</style>
